package com.smart.translator.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.textfield.TextInputEditText;
import com.smart.translator.MainActivity;
import com.smart.translator.R;
import com.smart.translator.data.ApiResponse;
import com.smart.translator.data.User;
import com.smart.translator.data.UserApiService;
import com.smart.translator.util.UserManager;
import com.smart.translator.util.NetworkUtils;
import java.util.concurrent.CompletableFuture;

/**
 * 登录注册Activity
 */
public class LoginActivity extends AppCompatActivity {
    private static final String TAG = "LoginActivity";
    
    // UI组件
    private TabLayout tabLayout;
    private View loginForm;
    private View registerForm;
    private TextInputEditText etLoginUsername, etLoginPassword;
    private TextInputEditText etRegisterUsername, etRegisterPhone, etRegisterEmail;
    private TextInputEditText etRegisterPassword, etRegisterConfirmPassword;
    private MaterialButton btnLogin, btnRegister;
    private View progressBar;
    private View tvError;
    
    // 用户管理
    private UserManager userManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        
        // 初始化用户管理器
        userManager = UserManager.getInstance(this);
        
        // 检查是否已登录
        if (userManager.isLoggedIn()) {
            Log.d(TAG, "用户已登录，直接跳转到主界面");
            startMainActivity();
            return;
        }
        
        // 初始化UI
        initViews();
        setupListeners();
    }

    /**
     * 初始化UI组件
     */
    private void initViews() {
        tabLayout = findViewById(R.id.tabLayout);
        loginForm = findViewById(R.id.loginForm);
        registerForm = findViewById(R.id.registerForm);
        
        // 登录表单
        etLoginUsername = findViewById(R.id.etLoginUsername);
        etLoginPassword = findViewById(R.id.etLoginPassword);
        btnLogin = findViewById(R.id.btnLogin);
        
        // 注册表单
        etRegisterUsername = findViewById(R.id.etRegisterUsername);
        etRegisterPhone = findViewById(R.id.etRegisterPhone);
        etRegisterEmail = findViewById(R.id.etRegisterEmail);
        etRegisterPassword = findViewById(R.id.etRegisterPassword);
        etRegisterConfirmPassword = findViewById(R.id.etRegisterConfirmPassword);
        btnRegister = findViewById(R.id.btnRegister);
        
        // 通用组件
        progressBar = findViewById(R.id.progressBar);
        tvError = findViewById(R.id.tvError);
    }

    /**
     * 设置监听器
     */
    private void setupListeners() {
        // Tab切换监听
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab.getPosition() == 0) {
                    // 登录
                    loginForm.setVisibility(View.VISIBLE);
                    registerForm.setVisibility(View.GONE);
                } else {
                    // 注册
                    loginForm.setVisibility(View.GONE);
                    registerForm.setVisibility(View.VISIBLE);
                }
                hideError();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {}

            @Override
            public void onTabReselected(TabLayout.Tab tab) {}
        });

        // 登录按钮
        btnLogin.setOnClickListener(v -> performLogin());

        // 注册按钮
        btnRegister.setOnClickListener(v -> performRegister());
    }

    /**
     * 执行登录
     */
    private void performLogin() {
        // 检查网络连接
        if (!NetworkUtils.isNetworkConnected(this)) {
            showError("网络连接失败，请检查网络设置");
            return;
        }

        String username = etLoginUsername.getText().toString().trim();
        String password = etLoginPassword.getText().toString().trim();

        // 验证输入
        if (TextUtils.isEmpty(username)) {
            showError("请输入用户名/手机号/邮箱");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            showError("请输入密码");
            return;
        }

        // 显示加载状态
        setLoading(true);
        hideError();

        // 调用登录API
        CompletableFuture<ApiResponse<User>> loginFuture = UserApiService.login(this, username, password);
        loginFuture.thenAcceptAsync(response -> {
            runOnUiThread(() -> {
                setLoading(false);
                if (response.isSuccess()) {
                    // 登录成功
                    User user = response.getData();
                    userManager.saveUser(user);
                    Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "登录成功: " + user.getUsername());
                    startMainActivity();
                } else {
                    // 登录失败
                    showError(response.getError());
                    Log.e(TAG, "登录失败: " + response.getError());
                }
            });
        }).exceptionally(throwable -> {
            runOnUiThread(() -> {
                setLoading(false);
                showError("网络请求失败，请检查网络连接");
                Log.e(TAG, "登录异常", throwable);
            });
            return null;
        });
    }

    /**
     * 执行注册
     */
    private void performRegister() {
        // 检查网络连接
        if (!NetworkUtils.isNetworkConnected(this)) {
            showError("网络连接失败，请检查网络设置");
            return;
        }

        String username = etRegisterUsername.getText().toString().trim();
        String phone = etRegisterPhone.getText().toString().trim();
        String email = etRegisterEmail.getText().toString().trim();
        String password = etRegisterPassword.getText().toString().trim();
        String confirmPassword = etRegisterConfirmPassword.getText().toString().trim();

        // 验证输入
        if (TextUtils.isEmpty(username)) {
            showError("请输入用户名");
            return;
        }
        if (TextUtils.isEmpty(phone)) {
            showError("请输入手机号");
            return;
        }
        if (TextUtils.isEmpty(email)) {
            showError("请输入邮箱");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            showError("请输入密码");
            return;
        }
        if (TextUtils.isEmpty(confirmPassword)) {
            showError("请确认密码");
            return;
        }
        if (!password.equals(confirmPassword)) {
            showError("两次输入的密码不一致");
            return;
        }
        if (password.length() < 6) {
            showError("密码长度至少6位");
            return;
        }

        // 验证手机号格式
        if (!phone.matches("^1[3-9]\\d{9}$")) {
            showError("请输入正确的手机号格式");
            return;
        }

        // 验证邮箱格式
        if (!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
            showError("请输入正确的邮箱格式");
            return;
        }

        // 显示加载状态
        setLoading(true);
        hideError();

        // 调用注册API
        CompletableFuture<ApiResponse<User>> registerFuture = UserApiService.register(this, username, phone, email, password);
        registerFuture.thenAcceptAsync(response -> {
            runOnUiThread(() -> {
                setLoading(false);
                if (response.isSuccess()) {
                    // 注册成功
                    Toast.makeText(this, "注册成功，请登录", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "注册成功");
                    // 切换到登录页面
                    tabLayout.selectTab(tabLayout.getTabAt(0));
                    // 清空注册表单
                    clearRegisterForm();
                } else {
                    // 注册失败
                    showError(response.getError());
                    Log.e(TAG, "注册失败: " + response.getError());
                }
            });
        }).exceptionally(throwable -> {
            runOnUiThread(() -> {
                setLoading(false);
                showError("网络请求失败，请检查网络连接");
                Log.e(TAG, "注册异常", throwable);
            });
            return null;
        });
    }

    /**
     * 显示错误信息
     */
    private void showError(String message) {
        if (tvError instanceof android.widget.TextView) {
            ((android.widget.TextView) tvError).setText(message);
            tvError.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏错误信息
     */
    private void hideError() {
        tvError.setVisibility(View.GONE);
    }

    /**
     * 设置加载状态
     */
    private void setLoading(boolean loading) {
        progressBar.setVisibility(loading ? View.VISIBLE : View.GONE);
        btnLogin.setEnabled(!loading);
        btnRegister.setEnabled(!loading);
    }

    /**
     * 清空注册表单
     */
    private void clearRegisterForm() {
        etRegisterUsername.setText("");
        etRegisterPhone.setText("");
        etRegisterEmail.setText("");
        etRegisterPassword.setText("");
        etRegisterConfirmPassword.setText("");
    }

    /**
     * 启动主Activity
     */
    private void startMainActivity() {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }

    @Override
    public void onBackPressed() {
        // 如果用户未登录，不允许返回
        if (!userManager.isLoggedIn()) {
            Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show();
            return;
        }
        super.onBackPressed();
    }
} 